<template>
  <view>
    <canvas :style="{ width: canvasW + 'px', height: canvasH + 'px' }"  canvas-id="poster" id="poster"></canvas>
    <uni-popup ref="popup" type="center" :boxStyle="{'background-color': 'rgba(0,0,0,0)','overflow-y': 'unset'}" background-color="none">
      <!--关闭-->
      <view class="close-box" @click="close">
        <image class="close-img" src="/static/icon/icon_del.png"/>
      </view>

      <!--海报-->
      <view class="share-box flex-col">
        <view class="share-cover flex-col">
          <image class="share-cover-img" :src="cover"/>
        </view>
        <view class="desc-box flex-row">
          <view class="slogan-list">
            <view class="desc-info" v-for="(text, index) in slogan" :key="index" :style="{'-webkit-line-clamp': lines}">
              {{text}}
            </view>
          </view>
          <view class="qr-code-box flex-col">

            <image class="qr-code-img" :src="qrcode"/>
          </view>
        </view>
      </view>

      <!--保存-->
      <view class="save-box" @click="createPosterHandle">
        <view class="save-mod">
          <image class="save-img" src="/static/icon/save-poster.png"/>
        </view>
        <text class="save-title">保存图片</text>
      </view>

    </uni-popup>

    <tki-qrcode
        ref="qrcodeRef"
        :val="qrcodeVal"
        @result="qrR" />
  </view>
</template>

<script>
  import tkiQrcode from '@/components/tki-qrcode/tki-qrcode.vue'
  import {base64ToPath} from "../js_sdk/image-tools";
	export default {
    components:{
      tkiQrcode
    },
		data() {
			return {
        qrcode: '',
        canvasW: 364,
        canvasH: 564,
        drawing: false, // 绘制中
			};
		},
		props:{
      qrcodeVal:{
        type: String,
        default: 'https://www.ggshop1688.com/static/app/index.html?v1&share=ymyx@gs@id2047'
      },
      lines:{
        type: Number,
        default: 3
      },
      cover:{
        type: String,
        default:'/static/images/goods-share.png'
      },
      slogan:{
        type:Array,
        default: ['分享海报'],
      },

		},
    mounted() {
      this.creatQrcode()
      // this.coverSrc = coverPaths[this.cover]
		},
    destroyed(){
      this.drawing = false;
    },
		methods:{
      open(){
        // 通过组件定义的ref调用uni-popup方法 ,如果传入参数 ，type 属性将失效 ，仅支持 ['top','left','bottom','right','center']
        this.$refs.popup.open('top')
      },
      close(){
        this.$refs.popup.close()
      },
      creatQrcode() {
        this.$refs.qrcodeRef?._makeCode()
      },
      qrR(res) {
        this.qrcode = res;
      },
      // 生成图片并下载
      async createPosterHandle(){
        if (this.drawing){
          return ;
        }
        this.drawing = true;
        // 判断临时文件是否存在
        if (!!this.tempFilePath){
          this.downFile()
          return;
        }

        try{
          uni.showToast({
            icon:'loading',
            mask:true,
            duration:10000,
            title: '海报绘制中',
          });
          let context = uni.createCanvasContext('poster')
          // 当前Y值
          let currentY = 0;
          // 商品图
          const coverImage = await this.getImageInfo(this.cover)
          // 二维码
          const qrCodeImage = await this.getImageInfo(this.qrcode)
          if (!coverImage.path || !qrCodeImage.path){
            throw '图片资源加载失败！'
          }
          // const {windowWidth, windowHeight} = await this.getSystemInfo();
          // 图片高 361
          let coverH = 461;
          // 二维码 70
          let qrcodeWH = 70
          // 边距 12
          let textML = 12
          // 文字 215
          let textLen = 215;
          // 图片与二维码距离 12
          let distanceHQ = 10;
          // 文字与二维码距离 22
          let distanceTQ = 12;
          // canvas 长宽
          this.canvasW = 332;
          this.canvasH = 554;

          // 背景色
          context.setFillStyle('#3f19a1'); // 默认白色
          context.fillRect(0, 0, this.canvasW, 100) // fillRect(x,y,宽度，高度)
          context.setFillStyle('#fff'); // 默认白色
          context.fillRect(0, 100, this.canvasW, this.canvasH - 100) // fillRect(x,y,宽度，高度)

          // 图片
          context.drawImage(coverImage.path, 0, currentY, this.canvasW, coverH);
          currentY = coverH + distanceHQ;
          // 二维码
          context.drawImage(
              qrCodeImage.path,
              0,
              0,
              qrCodeImage.width,
              qrCodeImage.height,
              this.canvasW - qrcodeWH - distanceTQ,
              currentY,
              qrcodeWH,
              qrcodeWH
          );

          // 3、绘制商品标题，多余文字自动换行
          context.setFontSize(14); // setFontSize() 设置字体字号
          context.setFillStyle('#333'); // setFillStyle() 设置字体颜色
          this.slogan.forEach(slogan=>{
            const {currentY: newCurrentY} = this.drawText(context, slogan, textML, currentY+12, textLen)
            currentY = newCurrentY+10;
          })

          context.draw(true, (ret)=>{ // draw方法 把以上内容画到 canvas 中。
            console.log(ret)
            uni.showToast({
              icon:'none',
              mask:true,
              title: '正在下载',
            });
            // this.tempFilePath = ret.tempFilePath;
            setTimeout(()=>this.downFile(), 500);
          })
        }catch (error){
          uni.showToast({
            icon:'none',
            mask:true,
            title: error,
          });
          this.drawing = true;
        }

      },
      // h5 下载图片
      downloadFile(content, filename) {
        var a = document.createElement('a')
        var blob = new Blob([content])
        var url = window.URL.createObjectURL(blob)
        a.href = url
        a.download = filename
        a.click()
        window.URL.revokeObjectURL(url)
      },
      download(url, filename) {
        let self = this;
        this.ajax(url, function(xhr) {
          self.downloadFile(xhr.response, filename)
        }, {
          responseType: 'blob'
        })
      },
      ajax(url, callback, options) {
        window.URL = window.URL || window.webkitURL
        var xhr = new XMLHttpRequest()
        xhr.open('get', url, true)
        if (options.responseType) {
          xhr.responseType = options.responseType
        }
        xhr.onreadystatechange = function() {
          if (xhr.readyState === 4 && xhr.status === 200) {
            callback(xhr)
          }
        }
        xhr.send()
      },

      // 下载临时文件
      downFile(){
        let self = this;
        uni.canvasToTempFilePath({ // 保存canvas为图片
          canvasId: 'poster',
          quality: 0.1,
          // destWidth: this.canvasW * 10,
          // destHeight: this.canvasH * 10,
          success: async function(res) {
            // 在H5平台下，tempFilePath 为 base64, // 图片提示跨域 H5保存base64失败，APP端正常输出临时路径
            // 需条件编译的代码
            base64ToPath(res.tempFilePath).then(path => {
              console.log('path========>', path)
              // window.location.href = path;
                })
                .catch(error => {
                  console.log('error========>', error)
                })

            // #ifdef H5
            self.download(res.tempFilePath, `share_${Math.random().toString().replace('.', '')}.png`);
            // #endif

            // #ifdef APP-PLUS
            uni.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: function() {
                uni.showToast({
                  icon: 'none',
                  position: 'bottom',
                  title: "图片已下载至【相册】，请打开【相册】查看", // res.tempFilePath
                });
              }
            });
            // #endif
          } ,
          fail:(error)=>{
            throw error
          },
          complete: ()=>{
            this.drawing = false;
          }
        })
      },
      getImageInfo(image) {
        return new Promise((req, rej) => {
          uni.getImageInfo({
            src: image,
            success: function(res) {
              req(res)
            },
          });
        })
      },
      // 获取设备信息
      getSystemInfo(){
        return new Promise((req, rej) => {
          uni.getSystemInfo({
            success: function (res) {
              req(res)
            }
          });
        })
      },
      /**
       * 绘制文字
       * @param context
       * @param slogan  文字
       * @param currentX 起始位置X
       * @param currentY 起始位置Y
       * @param lineW 行宽
       * @param lines 限制行数
       * @constructor
       */
      drawText(context, slogan, currentX, currentY, lineW=300, lines=3){
        let cursor =  0; // 文字下标
        let textLineW = 0; // 一行中当前写入的位置
        let lineNum = 1; // 当前行数
        // let lineW = 300; // 行宽
        while (cursor < slogan.length){
          // 当前文字
          let text = slogan.substr(cursor, 1);
          // 当前文字宽度
          let textW = context.measureText(text).width;

          // 判断文字是否写满一行 否：继续写，是：换到下一行
          if (textLineW < lineW){
            // 判断是否限制了行数 超过显示省略号
            if (textLineW >= (lineW-30) && lines === lineNum){
              text += '...';
              cursor = 99999; // 设置跳出循环
            }
            context.fillText(text, textLineW + currentX, currentY);
          }else{
            lineNum++;
            currentY += 20;
            textLineW = 0;
            context.fillText(text, textLineW + currentX, currentY);
          }
          textLineW += textW
          cursor++;
        }

        return {context, currentY};
      },
		}
	}
</script>

<style lang='scss'>
.poster{
  display: none;
}
.share-box {

  border-radius: 40upx;
  z-index: 44;
  height: 800upx;
  width: 600upx;
  margin: 0 auto;
  position: relative;
  .share-cover{
    height: 650upx;
    width: 100%;
    .share-cover-img{
      height: 100%;
      width: 100%;
    }
  }
  .desc-box{
    padding: 20upx;
    overflow: hidden;
    height: 180upx;
    width: 100%;
    display: flex;
    //justify-content: space-around;
    background-color: white;
    border-radius:0upx  0upx 20upx 20upx ;

    .slogan-list{
      width: 400rpx;
      margin-right: 30upx;
      .desc-info{
        float: left;
        width: 400rpx;
        font-size: 24rpx;
        line-height: 40rpx;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow:ellipsis;
      }
    }



    .qr-code-box{
      float: right;
      height: 130rpx;
      align-self: center;
      width: 130rpx;
      .qr-code-img{
        height: 100%;
        width: 100%;
      }
    }
  }


}

.close-box{
  width: 60upx;
  height: 60upx;
  float: right;
  position: absolute;
  top: -20upx;
  z-index: 99999;
  right: -20upx;
  .close-img{
    height: 100%;
    width: 100%;
  }
}

.save-box{
  margin: 40upx auto;
  width: 100px;
  .save-mod{
    margin: 0 auto;
    width: 80upx;
    height: 80upx;
    background-color: $base-color;
    display: flex;
    border-radius: 50%;
    .save-img{
      align-self: center;
      margin: 0 auto;
      display: block;
      width: 40upx;
      height: 40upx;
    }
  }

  .save-title{
    display: block;
    margin: 10upx auto;
    color: white;
    font-size: 26upx;
    text-align: center;
  }

}
</style>
